package pdm.yamba.service;

import pdm.yamba.MainApplication;
import pdm.yamba.R;
import pdm.yamba.dataAccess.DBProvider;
import pdm.yamba.feed.TwitterFeed;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class StatusUploadService extends Service {

	private HandlerThread _worker;
	private Handler _uiHandler;
	private Handler _workerHandler;
	private MainApplication application;
	
	@Override
	public void onCreate() 
	{
		super.onCreate();
		Log.v("Yamba", "StatusUploadService.onCreate() on thread " + Thread.currentThread().getId());
		
		_worker = new HandlerThread("StatusUploadService worker thread");
		_worker.start();
		
		_uiHandler = new Handler();
		_workerHandler = new Handler(_worker.getLooper(), new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) 
			{
				Log.v("Yamba", "handleMessage() on thread " + Thread.currentThread().getName());
				
				Bundle payload = msg.getData();
				
				application = (MainApplication) getApplication();
				DBProvider dbProvider = application.getDBProvider();
				if(application.isOnline())
				{
					publishOldMessages(dbProvider);					
					publishMessage(application, payload.getString("message"));

				}
				else
				{
					dbProvider.open();
					dbProvider.insertMessage(payload.getString("message"));
				    dbProvider.close();						
				}
				stopSelf(msg.arg1);
				return true;
			}
		});
	}

	@Override
	public int onStartCommand(final Intent intent, int flags, int startId) 
	{
		Log.v("Yamba", "StatusUploadService.onStartCommand() on thread " + Thread.currentThread().getId());
		
		Message msg = Message.obtain();
		msg.setData(intent.getExtras());
		_workerHandler.sendMessage(msg);
		
		return 0; // We will revisit this.
	}

	@Override
	public IBinder onBind(Intent intent) 
	{
		return null;
	}
	
	private void publishOldMessages(DBProvider dbProvider) {
		
		dbProvider.open();
	    Cursor c = dbProvider.getAllMessages();
	    int count = c.getCount();
	    if (c.moveToFirst()) {
	      do {
	    	  publishMessage(application, c.getString(c.getColumnIndex("message")));
	    	  dbProvider.deleteMessage(c.getLong(c.getColumnIndex("id")));
	      } while (c.moveToNext());
	    }
	    dbProvider.close();				
	}
	
	private void publishMessage(MainApplication application, String message)
	{
		application.PublishStatusViaService(message);
		
		_uiHandler.post(new Runnable() {
			@Override
			public void run() {
				
				Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show();
			}
		});
	}
}


